package com.sharding.transaction.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sharding.transaction.demo.entity.User;
import com.sharding.transaction.demo.mapper.UserMapper;
import com.sharding.transaction.demo.service.UserService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;

/**
 * @Classname UserServiceImpl
 * @Description 用户服务实现类
 * @Author 章国文 13120739083@163.com
 * @Date 2019-06-28 17:32
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource
    private DataSource dataSource;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public boolean save(User entity) {
        return super.save(entity);
    }
 
    @Override
    public List<User> getUserList() {
        QueryWrapper<User> objectLambdaQueryWrapper = new QueryWrapper<>();
        return baseMapper.selectList(objectLambdaQueryWrapper);
    }

    @Override
    @Transactional
    public User deductionAccount(Long userId, Double price) {
        LOGGER.info("dataSource: " + dataSource);
        String xid = RootContext.getXID();
        LOGGER.info("reduce account balance in transaction: " + xid);
        int res = baseMapper.deductionAccount(userId, price);
        if(res > 0){
            return getById(userId);
        }
        throw new RuntimeException("用户余额更新失败！！！");
    }

}